package com.vmix.android.vmixsdk.rds;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.vmix.android.vmixsdk.config.VmixConfig;
import com.vmix.android.vmixsdk.exception.VmixException;

/**
 * Operation that makes request the VMIX media play service
 * 
 * @author lei
 *
 */
public class PlayVideoOperation extends AbstractOperation {

	protected String playToken = "";
	
	/**
	 * 
	 * @param playToken
	 */
	public PlayVideoOperation( String playToken ) {
		
		this.playToken = playToken;
		
		this.serviceUrl = VmixConfig.PLAY;
	}
	
	/**
	 * 
	 * @return
	 * @throws VmixException
	 */
	public String process() throws VmixException {
		
		// build out the service url
		this.serviceUrl += "token=" + this.playToken + "&output=xml";
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		try {
			// build out new url object
			URL url = new URL( this.serviceUrl );
			URLConnection connection = url.openConnection();
			
			HttpURLConnection httpConnection = (HttpURLConnection)connection;
			
			// get respone code
			int responseCode = httpConnection.getResponseCode();
			
			// if the response code is not ok
			if( responseCode != HttpURLConnection.HTTP_OK ) {
				throw new HttpException();
			}
			
			Log.v("getCollectionsOperation", "HTTP Status: " + responseCode);
			
			InputStream inputStream = httpConnection.getInputStream();
			
			DocumentBuilder builder = factory.newDocumentBuilder();
			
			Document dom = builder.parse( inputStream );
			Element root = dom.getDocumentElement();
			NodeList playUrls = root.getElementsByTagName( "play_url" );
		
			// we just need the first node
			Node playUrl = playUrls.item( 0 );
			
			return playUrl.getFirstChild().getNodeValue();
		
		}
		catch( Exception e ) {
		
			throw new VmixException( e.getMessage() );
		
		}
		
	}
	
}
